package com.youhome.service.impl;

import com.aliyun.oss.OSSClient;
import com.youhome.common.Constant;
import com.youhome.config.OSSConfig;
import com.youhome.service.UploadService;
import com.youhome.utils.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * Created by chen365 on 2018/12/12.
 */
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {
    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String upload(MultipartFile file, String folder) {
        try {
            String originalFileName = file.getOriginalFilename();
            String ext = FilenameUtils.getExtension(originalFileName);
            String newFileName = UUID.randomUUID().toString() + "." + ext;
            String uploadPath = Constant.TEMP;
            File newFile = new File(uploadPath, newFileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);

            OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            String md5key = OSSUtil.uploadObject2OSS(ossClient, newFile, ossConfig.getBacketName(), folder);
            log.info("上传后的文件MD5数字唯一签名:" + md5key);
            FileUtils.deleteQuietly(newFile);
            String imageUrl = folder + "/" + newFileName;
            // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url
            return imageUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
